package com.by.basicgateway.intercept.filter;

import com.by.toolkit.consts.WebGlobalConst;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class AdminRefererMapProjectInfoGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

    @Resource
    private GatewayFilterSupport gatewayFilterSupport;

    private static final List<String> UN_IGNORE_HEADERS = Lists.newArrayList(
            "projectid",
            "menupath"
    );

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            String referer = request.getHeaders().getFirst(WebGlobalConst.REFERER);
            if (StringUtils.isBlank(referer)) {
                log.info("[AdminRefererMapProjectInfoGatewayFilter][filter] path:[{}] headerProjectCodeIsNull refererIsNull", path);
                return chain.filter(exchange);
            }

            Map<String, String> projectInfoMap = gatewayFilterSupport.adminDomainMapInfo(referer);
            log.info("[AdminRefererMapProjectInfoGatewayFilterFactory][filter] path:[{}] referer:[{}] projectInfoMap:[{}]", path, referer, projectInfoMap);
            return chain.filter(gatewayFilterSupport.dealHeader(exchange, projectInfoMap, UN_IGNORE_HEADERS));
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return List.of("require");
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Config {

        private boolean require;

    }

}
